package com.atguigu.spzx.manager.utils;


import com.atguigu.spzx.model.entity.system.SysMenu;

import java.util.ArrayList;
import java.util.List;

/**
 * 构建树形工具类
 *
 * @author Henry
 * @version 1.0
 * @program: spzx-parent
 * @create: 2025/6/10 下午8:29
 */


public class MenuHelper {

    /**
     * 使用递归方法建菜单
     * @param sysMenuList
     * @return
     */
    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        ArrayList<SysMenu> trees = new ArrayList<>();
        for(SysMenu sysMenu : sysMenuList) {
            if(sysMenu.getParentId().longValue() == 0){
                trees.add(findChildren(sysMenu, sysMenuList));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    private static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> treeNodes){
        sysMenu.setChildren(new ArrayList<SysMenu>());
        for(SysMenu it : treeNodes){
            if(sysMenu.getId().longValue() == it.getParentId().longValue()){
                //if (sysMenu.getChildren() == null) {
                //    sysMenu.setChildren(new ArrayList<>());
                //}
                sysMenu.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return sysMenu;
    }
}
